import  { useState, useEffect, useRef } from 'react';
import { 
  Card, Row, Col, Typography, Tabs, Table, 
  Badge, Divider, Avatar, Spin
} from 'antd';
import * as echarts from 'echarts';
import { 
  StarOutlined, ClockCircleOutlined, 
  UserOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';

const { Title, Paragraph } = Typography;
const { TabPane } = Tabs;

// 模拟项目详情数据
//理疗项目分析详情(预约分析)
const getTreatmentDetail = (name) => {
  // 基础数据保持不变
  const baseData = {
    '推拿按摩': {
      id: 'S001',
      name: '推拿按摩',
      description: '通过专业手法对身体穴位和肌肉进行按摩，促进血液循环，缓解肌肉疲劳和紧张，改善身体亚健康状态。',
      duration: '60分钟',
      price: 180,
      discountPrice: 158,
      popularity: 320,
      satisfaction: 96,
      image: 'https://p9-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/1b2acebfebd94522ac6688df2e6e2a92.png~tplv-a9rns2rl98-24:720:720.png',
      features: [
        '缓解肌肉紧张和疼痛',
        '改善局部血液循环',
        '放松身心，缓解压力',
        '提高睡眠质量'
      ],
      suitablePeople: [
        '长期伏案工作的办公室人群',
        '运动后肌肉疲劳人群',
        '颈肩腰腿痛患者',
        '压力大、睡眠质量差的人群'
      ],
      therapist: [
        { name: '李员工', experience: '10年', rating: 4.9 },
        { name: '陈员工', experience: '8年', rating: 4.8 },
        { name: '赵员工', experience: '6年', rating: 4.7 }
      ],
      monthlyData: Array.from({ length: 6 }, (_, i) => ({
        month: dayjs().subtract(5 - i, 'month').format('MM月'),
        预约量: 45 + Math.floor(Math.random() * 15) + i * 5,
        满意度: 92 + Math.floor(Math.random() * 5)
      }))
    },
    '针灸治疗': {
      id: 'S002',
      name: '针灸治疗',
      description: '运用传统中医针灸理论，通过针刺特定穴位，调节人体气血运行，达到治疗疾病和养生保健的目的。',
      duration: '45分钟',
      price: 260,
      discountPrice: 228,
      popularity: 250,
      satisfaction: 98,
      image: 'https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/12078600632f4391bcf3805357ac3011.png~tplv-a9rns2rl98-24:720:720.png',
      features: [
        '调节气血，平衡阴阳',
        '针对性治疗特定病症',
        '无药物副作用',
        '疗效持久'
      ],
      suitablePeople: [
        '颈肩腰腿痛等疼痛性疾病患者',
        '失眠、焦虑等神经系统疾病患者',
        '消化系统功能紊乱人群',
        '亚健康调理人群'
      ],
      therapist: [
        { name: '王员工', experience: '12年', rating: 4.9 },
        { name: '李员工', experience: '10年', rating: 4.8 },
        { name: '张员工', experience: '7年', rating: 4.7 }
      ],
      monthlyData: Array.from({ length: 6 }, (_, i) => ({
        month: dayjs().subtract(5 - i, 'month').format('MM月'),
        预约量: 35 + Math.floor(Math.random() * 15) + i * 4,
        满意度: 94 + Math.floor(Math.random() * 4)
      }))
    },
    // 其他项目数据保持不变...
    '艾灸养生': {
      id: 'S003',
      name: '艾灸养生',
      description: '通过燃烧艾绒产生的温热刺激体表穴位或特定部位，激发经气的活动来调整人体紊乱的生理生化功能。',
      duration: '50分钟',
      price: 220,
      discountPrice: 198,
      popularity: 180,
      satisfaction: 95,
      image: 'https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/e61e5acdb7564d9bbdd03d1690c96b68.png~tplv-a9rns2rl98-24:720:720.png',
      features: [
        '温通经络，驱散寒邪',
        '促进血液循环',
        '增强免疫力',
        '调理内分泌'
      ],
      suitablePeople: [
        '体质虚寒人群',
        '女性宫寒、痛经患者',
        '关节疼痛人群',
        '免疫力低下人群'
      ],
      therapist: [
        { name: '陈员工', experience: '9年', rating: 4.8 },
        { name: '赵员工', experience: '6年', rating: 4.7 },
        { name: '刘员工', experience: '5年', rating: 4.6 }
      ],
      monthlyData: Array.from({ length: 6 }, (_, i) => ({
        month: dayjs().subtract(5 - i, 'month').format('MM月'),
        预约量: 30 + Math.floor(Math.random() * 12) + i * 3,
        满意度: 93 + Math.floor(Math.random() * 4)
      }))
    }
    // 可以继续添加其他项目...
  };
  
  return baseData[name] || baseData['推拿按摩'];
};

// 模拟客户评价数据
const generateReviews = (count) => {
  const comments = [
    "效果很好，做完之后感觉全身轻松了很多，下次还会再来。",
    "员工手法专业，讲解详细，整个过程很舒适。",
    "环境干净整洁，服务态度好，项目体验非常满意。",
    "做完之后症状明显缓解，值得推荐给有需要的朋友。",
    "性价比高，效果超出预期，会定期来做护理。"
  ];
  
  return Array.from({ length: count }, (_, i) => ({
    id: i + 1,
    customer: `客户${i + 1}`,
    rating: 4 + Math.floor(Math.random() * 2),
    date: dayjs().subtract(i + 1, 'day').format('YYYY-MM-DD'),
    comment: comments[i % comments.length]
  }));
};

const TreatmentDetailModal = (props) => {
  // 只使用 props.data，不依赖 visible 和 onClose
  const [loading, setLoading] = useState(true);
  const [detail, setDetail] = useState(null);
  const [reviews, setReviews] = useState([]);
  
  // 加载数据 - 仅依赖 props.data
  useEffect(() => {
    if (props.data?.name) {
      setLoading(true);
      
      // 模拟API请求延迟
      const timer = setTimeout(() => {
        const treatmentData = getTreatmentDetail(props.data.name);
        setDetail(treatmentData);
        setReviews(generateReviews(5));
        setLoading(false);
      }, 600);
      
      // 清理函数
      return () => clearTimeout(timer);
    }
  }, [props.data?.name]); // 仅监听 data.name 的变化
  
  // 图表相关
  const trendChartRef = useRef(null);
  const trendChartContainer = useRef(null);

  // 初始化图表
  useEffect(() => {
    if (!loading && detail && trendChartContainer.current) {
      // 销毁现有图表
      if (trendChartRef.current) {
        trendChartRef.current.dispose();
      }
      
      // 创建新图表
      trendChartRef.current = echarts.init(trendChartContainer.current);
      
      // 配置图表
      const option = {
        title: {
          text: '近6个月项目数据趋势',
          left: 'center',
          textStyle: { fontSize: 14 }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' }
        },
        legend: {
          data: ['预约量', '满意度(%)'],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: detail.monthlyData.map(item => item.month)
        },
        yAxis: [
          { type: 'value', name: '预约量' },
          { type: 'value', name: '满意度(%)', max: 100 }
        ],
        series: [
          {
            name: '预约量',
            type: 'bar',
            data: detail.monthlyData.map(item => item.预约量),
            itemStyle: { color: '#8B5A2B' }
          },
          {
            name: '满意度(%)',
            type: 'line',
            yAxisIndex: 1,
            data: detail.monthlyData.map(item => item.满意度),
            lineStyle: { color: '#52c41a' },
            symbol: 'circle',
            itemStyle: { color: '#52c41a' }
          }
        ]
      };
      
      trendChartRef.current.setOption(option);
      
      // 窗口大小变化时重绘
      const handleResize = () => {
        trendChartRef.current?.resize();
      };
      
      window.addEventListener('resize', handleResize);
      
      // 清理函数
      return () => {
        window.removeEventListener('resize', handleResize);
        trendChartRef.current?.dispose();
      };
    }
  }, [loading, detail]);

  // 评价列定义
  const reviewColumns = [
    {
      title: '客户',
      dataIndex: 'customer',
      key: 'customer',
      render: (text) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Avatar icon={<UserOutlined />} style={{ marginRight: 8 }} />
          <span>{text}</span>
        </div>
      )
    },
    {
      title: '评分',
      dataIndex: 'rating',
      key: 'rating',
      render: (score) => (
        <div>
          {[...Array(5)].map((_, i) => (
            <StarOutlined 
              key={i} 
              style={{ 
                color: i < score ? '#faad14' : '#ccc',
                marginRight: 2
              }} 
            />
          ))}
        </div>
      )
    },
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date'
    },
    {
      title: '评价内容',
      dataIndex: 'comment',
      key: 'comment'
    }
  ];

  // 员工列定义
  const therapistColumns = [
    {
      title: '员工',
      dataIndex: 'name',
      key: 'name',
      render: (text) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Avatar style={{ marginRight: 8, backgroundColor: '#8B5A2B' }}>{text.charAt(0)}</Avatar>
          <span>{text}</span>
        </div>
      )
    },
    {
      title: '从业经验',
      dataIndex: 'experience',
      key: 'experience'
    },
    {
      title: '平均评分',
      dataIndex: 'rating',
      key: 'rating',
      render: (score) => (
        <div>
          {[...Array(5)].map((_, i) => (
            <StarOutlined 
              key={i} 
              style={{ 
                color: i < Math.floor(score) ? '#faad14' : '#ccc',
                marginRight: 2
              }} 
            />
          ))}
          <span style={{ marginLeft: 5 }}>{score}</span>
        </div>
      )
    }
  ];

  // 加载状态显示
  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: 60 }}>
        <Spin size="large" tip="加载项目详情中..." />
      </div>
    );
  }

  // 数据未加载完成时不渲染内容
  if (!detail) return null;

  // 移除了外部的 Modal 组件，仅保留内容部分
  return (
    <div className="modal-box">
      {/* 项目基本信息 */}
      <Row gutter={[24, 16]} style={{ marginBottom: 20 }}>
        <Col xs={24} md={8}>
          <div style={{ 
            width: '100%', 
            height: 200, 
            borderRadius: 8,
            overflow: 'hidden',
            position: 'relative'
          }}>
            <img 
              src={detail.image} 
              alt={`${detail.name}图片`} 
              style={{ 
                width: '100%', 
                height: '100%', 
                objectFit: 'cover',
                transition: 'transform 0.5s ease'
              }}
              onMouseOver={(e) => e.currentTarget.style.transform = 'scale(1.05)'}
              onMouseOut={(e) => e.currentTarget.style.transform = 'scale(1)'}
            />
            <Badge 
              count={`满意度 ${detail.satisfaction}%`} 
              style={{ 
                position: 'absolute', 
                top: 10, 
                right: 10,
                backgroundColor: '#52c41a'
              }} 
            />
          </div>
        </Col>
        
        <Col xs={24} md={16}>
          <div style={{ marginBottom: 10 }}>
            <Title level={4} style={{ margin: 0, display: 'inline-block' }}>
              {detail.name}
            </Title>
            <Badge 
              status="success" 
              text="热门项目" 
              style={{ marginLeft: 10 }} 
            />
          </div>
          
          <Paragraph style={{ marginBottom: 15 }}>
            {detail.description}
          </Paragraph>
          
          <Row gutter={[16, 8]}>
            <Col xs={12} sm={6}>
              <div style={{ display: 'flex', alignItems: 'center', color: '#666' }}>
                <ClockCircleOutlined style={{ marginRight: 5, color: '#8B5A2B' }} />
                <span>时长: {detail.duration}</span>
              </div>
            </Col>
            <Col xs={12} sm={6}>
              <div style={{ display: 'flex', alignItems: 'center', color: '#666' }}>
                <UserOutlined style={{ marginRight: 5, color: '#8B5A2B' }} />
                <span>累计预约: {detail.popularity}人</span>
              </div>
            </Col>
            <Col xs={12} sm={6}>
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <span style={{ textDecoration: 'line-through', color: '#999', marginRight: 10 }}>
                  ¥{detail.price}
                </span>
                <span style={{ color: '#f5222d', fontSize: 18, fontWeight: 600 }}>
                  ¥{detail.discountPrice}
                </span>
              </div>
            </Col>
            <Col xs={12} sm={6}>
              <div style={{ display: 'flex', alignItems: 'center', color: '#666' }}>
                <StarOutlined style={{ marginRight: 5, color: '#52c41a' }} />
                <span>满意度: {detail.satisfaction}%</span>
              </div>
            </Col>
          </Row>
        </Col>
      </Row>
      
      <Divider />
      
      {/* 详情标签页 */}
      <Tabs defaultActiveKey="overview" animated>
        <TabPane tab="项目概览" key="overview">
          <Row gutter={[24, 24]}>
            <Col xs={24} lg={12}>
              <Card title="项目特点" bordered={false}>
                <ul style={{ paddingLeft: 20 }}>
                  {detail.features.map((feature, index) => (
                    <li key={index} style={{ 
                      marginBottom: 10, 
                      lineHeight: 1.6,
                      listStyleType: 'disc'
                    }}>
                      {feature}
                    </li>
                  ))}
                </ul>
              </Card>
            </Col>
            
            <Col xs={24} lg={12}>
              <Card title="适用人群" bordered={false}>
                <ul style={{ paddingLeft: 20 }}>
                  {detail.suitablePeople.map((people, index) => (
                    <li key={index} style={{ 
                      marginBottom: 10, 
                      lineHeight: 1.6,
                      listStyleType: 'disc'
                    }}>
                      {people}
                    </li>
                  ))}
                </ul>
              </Card>
            </Col>
            
            <Col xs={24}>
              <Card title="项目数据趋势" bordered={false}>
                <div 
                  ref={trendChartContainer} 
                  style={{ width: '100%', height: 300 }}
                ></div>
              </Card>
            </Col>
          </Row>
        </TabPane>
        
        <TabPane tab="服务员工  " key="therapist">
          <Card bordered={false}>
            <Table
              columns={therapistColumns}
              dataSource={detail.therapist}
              pagination={false}
              rowKey="name"
              style={{ marginTop: 10 }}
            />
          </Card>
        </TabPane>
        
        <TabPane tab="客户评价" key="reviews">
          <Card bordered={false}>
            <Table
              columns={reviewColumns}
              dataSource={reviews}
              pagination={{ pageSize: 3 }}
              rowKey="id"
              style={{ marginTop: 10 }}
            />
          </Card>
        </TabPane>
      </Tabs>
    </div>
  );
};

export default TreatmentDetailModal;
